//
//  PlTableViewExtension.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/12.
//

import Foundation
import UIKit
private var empty_placeholder_tag = UInt32(2002)
private var is_empty_tag = UInt32(3003)
extension UITableView:CustomMethodSwizzling{
    
    static func awake() {
        swizzledMethod
    }
    private static let swizzledMethod: ()={
        let oldSelector = #selector(reloadData)
        let newSelector = #selector(emptyRloadData)
        swizzlingForClass(UITableView.self, oldSelector: oldSelector, newSelector: newSelector)
    }()
    @objc func emptyRloadData(){
        self.emptyRloadData()
        self.checkDataCount()
    }
    var isEmpty:Bool{
        set{
            objc_setAssociatedObject(self, &is_empty_tag, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &is_empty_tag) as? Bool ?? true
        }
    }
    var placeholderView : PlaceholderView?{
        set{
            objc_setAssociatedObject(self, &empty_placeholder_tag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &empty_placeholder_tag) as? PlaceholderView
        }
    }
    
    func checkDataCount() {
        isEmpty = true
        let tempDataSource = self.dataSource
        var sections:Int?
        sections = tempDataSource?.numberOfSections?(in: self)
        if sections != nil {
            for index in 0..<sections! {
                guard let row = tempDataSource?.tableView(self, numberOfRowsInSection: index) else {
                    return
                }
                if row>0 {
                    isEmpty = false
                    break
                }
            }
        }
        self.placeholderView?.removeFromSuperview()
        if isEmpty{
            if self.placeholderView != nil{
                self.addSubview(self.placeholderView!)
                self.placeholderView?.frame = self.bounds
                if DataManager.login {
                    self.placeholderView?.reloadView()
                }else{
                    self.placeholderView?.reloadView(type: .NotLogined)
                }
            }
        }
    }
}
